// 导入用到的包
import { useEffect } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import type { RootState } from '@/types/store'

import highlight from 'highlight.js'

// 泛型函数基础
// function id<T>(value: T): T {
//   return value
// }

// 创建 useInitialState 函数（自定义 hook）
// 写法1：列举所有
// const useInitialState = (action: () => void, stateName: keyof RootState) => {
// 写法2：约束返回类型某一个
// const useInitialState = <StateName extends keyof RootState>(
//   action: () => void,
//   stateName: StateName
// ): RootState[StateName] => {
// 写法2-es5
function useInitialState<StateName extends keyof RootState>(
  action: () => void,
  stateName: StateName
) {
  const dispatch = useDispatch()
  const state = useSelector((state: RootState) => state[stateName])

  useEffect(() => {
    dispatch(action())
  }, [dispatch, action])

  return state
}

const useCodeLight = () => {
  // 文章详情 代码内容 高亮
  useEffect(() => {
    highlight.configure({
      // 忽略警告
      ignoreUnescapedHTML: true,
    })
    const dgHtmlDOM = document.querySelector('.dg-html')
    const codes = dgHtmlDOM?.querySelectorAll<HTMLElement>('pre code')
    // console.log(codes)
    if (codes && codes.length > 0) {
      codes.forEach((el) => {
        // 让每个 code 内容实现代码高亮
        highlight.highlightElement(el)
      })
    }
  }, [])
}

export { useInitialState, useCodeLight }
